from collections import OrderedDict
from pprint import pprint
import pymysql
import json


def save_dict_to_json_file(data, file_path):
    with open(file_path, 'w', encoding='utf-8') as json_file:
        json.dump(data, json_file, ensure_ascii=False, indent=4)

if __name__ == "__main__":
    db_laws = pymysql.Connect(
        host='nj-cdb-1mwvwkzt.sql.tencentcdb.com',
        port=63972,
        user='root',
        passwd='grow1234',
        db='stock_exchange'
    )

    # db_laws = pymysql.Connect(
    #     host='localhost',
    #     port=3306,
    #     user='root',
    #     passwd='123456',
    #     charset='utf8mb4',
    #     db='r4_local_stock_exchange_100'
    # )

    num = 1
    id_content_dict = OrderedDict()
    for num in range(1, 108180):
        print('正在获取详情页:', num)
        cursor = db_laws.cursor()
        cursor.execute("SELECT material_id, material_order, material_content FROM material_new WHERE material_id = %s", (num,))
        # query_results = cursor.fetchall()
        query_results = cursor.fetchone()
        材料ID = query_results[0]
        材料顺序 = query_results[1]
        材料内容 = query_results[2]
        if 材料顺序 != 0:
            id_content_dict[材料ID] = 材料内容
        print('材料ID:', 材料ID)
        print('材料顺序:', 材料顺序)
        print('材料内容:', 材料内容)
        # print(query_results)
        print('获取详情页结束:', num)
        print('============================================')
        cursor.close()
        # if num == 3:
        #     break
        #     print('+++++++++++++++++++++++++++++++++++++++++++++++')
        #     pprint(id_content_dict)
    db_laws.close()

    # 保存字典到 JSON 文件
    print('保存成json文件')
    file_path = '../data/R5_id_content_dict.json'  # 保存的文件路径
    save_dict_to_json_file(id_content_dict, file_path)
    print('保存成功')